<template>
  <div class="app-container">
    <div class="query-area">
      <a-form
        :model="queryParams"
        ref="queryRef"
        layout="inline"
        v-show="showSearch"
      >
        <a-form-item label="姓名" field="realName">
          <a-input
            v-model="queryParams.realName"
            placeholder="请输入姓名"
            allow-clear
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </a-form-item>
        <a-form-item label="手机号码" field="userName">
          <a-input
            v-model="queryParams.userName"
            placeholder="请输入手机号码"
            allow-clear
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" icon="Search" @click="handleQuery"
              >搜索</a-button
            >
            <a-button @click="resetQuery">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
    <div class="operation-area"></div>
    <div class="table-area">
      <a-table
        :columns="columns"
        :data="userList"
        :loading="loading"
        row-key="userId"
        :pagination="{
          total: total,
          current: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          showJumper: true,
          showTotal: true,
          showPageSize: true,
          pageSizeOptions: [10, 20, 30, 50, 100, 200]
        }"
        @page-change="tablePageChange"
        @page-size-change="tablePageSizeChange"
      >
        <!-- <template #status="{ record }">
        <a-switch
          v-model="record.status"
          checked-value="0"
          unchecked-value="1"
          @change="handleStatusChange(record)"
        ></a-switch>
      </template> -->
        <template #createTime="{ record }">
          <span>{{ parseTime(record.createTime) }}</span>
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-tooltip
              v-if="record.isAdmin === 1"
              content="管理员不可操作"
              position="top"
              mini
            >
              <a-button
                type="text"
                :disabled="record.isAdmin === 1"
                @click="handleUpdate(record)"
                >角色分配</a-button
              >
            </a-tooltip>
            <a-button
              v-else
              type="text"
              :disabled="record.isAdmin === 1"
              @click="handleUpdate(record)"
              >角色分配</a-button
            >
          </a-space>
        </template>
      </a-table>
    </div>
    <!-- 添加或修改用户配置对话框 -->
    <a-modal :title="title" v-model:visible="open" width="600px">
      <a-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <a-row>
          <a-col :span="24">
            <a-form-item label="角色" field="roleIds">
              <a-select v-model="form.roleIds" multiple placeholder="请选择">
                <a-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-row justify="end">
          <a-space>
            <a-button @click="cancel">取消</a-button>
            <a-button type="primary" @click="submitForm" :loading="okLoading"
              >确定</a-button
            >
          </a-space>
        </a-row>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="User">
import { getUser, listUser, updateUser } from '@/api/system/user'
import { allRoleList } from '@/api/system/role'
import { Message } from '@arco-design/web-vue'

const { proxy } = getCurrentInstance()
const queryRef = ref(null)
const userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')
const roleOptions = ref([])
const okLoading = ref(false)
const userRef = ref(null)

const columns = ref([
  {
    title: '姓名',
    dataIndex: 'realName'
  },
  {
    title: '所属部门',
    dataIndex: 'departmentName'
  },
  {
    title: '手机号码',
    dataIndex: 'userName'
  },

  // {
  //   title: '状态',
  //   slotName: 'status'
  // },
  {
    title: '创建时间',
    slotName: 'createTime'
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 200,
    align: 'center'
  }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    realName: undefined,
    userName: undefined,
    status: undefined
  },
  rules: {
    // roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value)).then((res) => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 分页变化
function tablePageChange(pageNum) {
  queryParams.value.pageNum = pageNum
  getList()
}

// 每页数据数量
function tablePageSizeChange(pageSize) {
  queryParams.value.pageSize = pageSize
  handleQuery()
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    roleIds: []
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false
  okLoading.value = false
  reset()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const userId = row.userId
  Promise.all([getUser(userId), allRoleList({ status: 0 })])
    .then((responses) =>
      Promise.all(
        responses.map((res) => {
          return res?.data || []
        })
      )
    )
    .then((results) => {
      // form.value = results[0]
      form.value = {
        userId: results[0].userId,
        roleIds: results[0].roleIds
      }
      roleOptions.value = results[1]
      open.value = true
      title.value = '角色分配'
    })
}

/** 提交按钮 */
function submitForm() {
  userRef.value.validate((errors) => {
    if (!errors) {
      okLoading.value = true
      updateUser(form.value)
        .then((response) => {
          Message.success('角色分配成功')
          open.value = false

          getList()
        })
        .finally(() => {
          okLoading.value = false
        })
    }
  })
}

getList()
</script>
